import { validatenull } from '@/utils/validate'
import { key } from '../config'

const keyName = key + '-'
/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
  let { name, content } = params
  name = keyName + name
  const obj = {
    dataType: typeof (content),
    content: content,
    datetime: new Date().getTime()
  }

  uni.setStorageSync(name, JSON.stringify(obj))
}
/**
 * 获取localStorage
 */

export const getStore = (params = {}) => {
  let { name, debug } = params
  name = keyName + name
  let obj = {}
  let content
  obj = uni.getStorageSync(name)
  if (validatenull(obj)) return
  try {
    obj = JSON.parse(obj)
  } catch (e) {
    return obj
  }
  if (debug) {
    return obj
  }
  if (obj.dataType === 'string') {
    content = obj.content
  } else if (obj.dataType === 'number') {
    content = Number(obj.content)
  } else if (obj.dataType === 'boolean') {
    content = (obj.content === 'true' || obj.content === 'TRUE')
  } else if (obj.dataType === 'object') {
    content = obj.content
  }
  return content
}
/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
  let { name } = params
  name = keyName + name
  uni.removeStorageSync(name)
}

/**
 * 获取全部localStorage
 */
export const getAllStore = (params = {}) => {
  const list = []
  const res = uni.getStorageInfoSync()
  for (let i = 0; i <= res.keys.length; i++) {
    list.push({
      name: res.keys[i],
      content: getStore({ name: res.keys[i] })
    })
  }
  return list
}

/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
  try {
    uni.clearStorageSync()
  } catch (e) {
    // error
  }
}
